<template>
  <section class="space-y-4 pb-16">
    <!-- 退出确认弹窗 -->
    <div v-if="showLogoutConfirm" class="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
      <div class="bg-white rounded-2xl p-6 w-full max-w-sm">
        <div class="text-center mb-4">
          <div class="text-lg font-semibold text-gray-900 mb-2">确认退出</div>
          <div class="text-gray-600">确定要退出登录吗？</div>
        </div>
        <div class="flex gap-3">
          <button
            @click="showLogoutConfirm = false"
            class="flex-1 py-2.5 border border-gray-300 text-gray-700 rounded-xl font-medium hover:bg-gray-50 transition-colors"
          >
            取消
          </button>
          <button
            @click="confirmLogout"
            class="flex-1 py-2.5 bg-red-500 text-white rounded-xl font-medium hover:bg-red-600 transition-colors"
          >
            确定
          </button>
        </div>
      </div>
    </div>

    <!-- 个人信息卡片 -->
    <div class="rounded-2xl overflow-hidden bg-gradient-to-br from-indigo-500 to-brand-600 text-white shadow-glass">
      <!-- 加载状态 -->
      <div v-if="loading" class="p-5 flex items-center gap-4">
        <div class="w-14 h-14 rounded-full bg-white/20 backdrop-blur-md flex items-center justify-center">
          <div class="animate-spin rounded-full h-6 w-6 border-b-2 border-white"></div>
        </div>
        <div class="space-y-2">
          <div class="h-4 bg-white/20 rounded w-32"></div>
          <div class="h-3 bg-white/20 rounded w-24"></div>
        </div>
      </div>

      <!-- 用户信息 -->
      <div v-else class="p-5 flex items-center gap-4">
        <div class="w-14 h-14 rounded-full bg-white/20 backdrop-blur-md flex items-center justify-center text-xl font-bold">
          {{ userInfo.name ? userInfo.name.charAt(0) : 'A' }}
        </div>
        <div>
          <div class="text-lg font-semibold">{{ userInfo.name || '用户' }}</div>
          <div class="text-sm text-white/80">
            {{ userInfo.phone || '未设置手机号' }}
          </div>
        </div>
      </div>
    </div>

    <!-- 钱包卡片 -->
    <div class="rounded-2xl overflow-hidden bg-gradient-to-br from-blue-500 to-purple-600 text-white shadow-glass">
      <div class="p-5">
        <!-- 顶部：标题和操作按钮 -->
        <div class="flex items-center justify-between mb-6">
          <div class="text-lg font-semibold">我的钱包</div>
          <div class="flex items-center gap-2">
            <button @click="goTo('/income-records')" class="text-sm bg-white/20 backdrop-blur-md px-3 py-1.5 rounded-full hover:bg-white/30 transition-colors">
              入账记录
            </button>
            <button @click="goTo('/withdraw-records')" class="text-sm bg-white/20 backdrop-blur-md px-3 py-1.5 rounded-full hover:bg-white/30 transition-colors">
              提现记录
            </button>
          </div>
        </div>

        <!-- 中间：金额显示 -->
        <div class="text-center mb-6">
          <div class="text-sm text-white/80 mb-2">账户余额</div>
          <div class="text-4xl font-bold">¥ {{ balance.toFixed(2) }}</div>
        </div>

        <!-- 底部：提现按钮 -->
        <div class="flex justify-end">
          <button @click="goTo('/withdraw')" class="bg-white text-blue-600 px-6 py-2.5 rounded-full font-medium hover:bg-blue-50 transition-colors shadow-md">
            提现
          </button>
        </div>
      </div>
    </div>

    <div class="rounded-2xl bg-white border border-gray-100 shadow-sm overflow-hidden">
      <ul class="divide-y divide-gray-100">
        <li>
          <button class="w-full px-4 py-4 flex items-center justify-between hover:bg-gray-50" @click="handleChangePassword">
            <span class="text-gray-800">修改密码</span>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-5 h-5 text-gray-400"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
          </button>
        </li>
        <li>
          <button class="w-full px-4 py-4 flex items-center justify-between hover:bg-gray-50" @click="showLogoutConfirm = true">
            <span class="text-red-600">退出登录</span>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-5 h-5 text-gray-400"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"/></svg>
          </button>
        </li>
      </ul>
    </div>
  </section>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { logout, getUserInfo } from '../api/auth'
import { getBalance } from '../api/my'

const router = useRouter()

// 用户信息
const userInfo = ref({})
const loading = ref(false)
const balance = ref(0)

// 银行信息数据 - 直接声明一个变量保存
const bankInfoData = ref({
  balance: 0,
  hasBankInfo: false,
  bankInfo: null
})

// 退出确认弹窗显示状态
const showLogoutConfirm = ref(false)

// 加载用户信息
const loadUserInfo = async () => {
  try {
    loading.value = true
    const result = await getUserInfo()

    if (result.success) {
      userInfo.value = result.data || {}
      console.log('用户信息加载成功:', userInfo.value)
    } else {
      console.error('加载用户信息失败:', result.message)
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
  } finally {
    loading.value = false
  }
}

// 加载余额信息
const loadBalance = async () => {
  try {
    const result = await getBalance()

    if (result.success) {
      // 直接保存到变量中，简化处理
      const balanceStr = result.data?.balance || '0.00'
      bankInfoData.value = {
        balance: parseFloat(balanceStr) || 0,
        hasBankInfo: result.data?.hasBankInfo || false,
        bankInfo: result.data?.bankInfo || null
      }

      // 同时更新模板中的balance变量
      balance.value = bankInfoData.value.balance

      console.log('余额和银行信息加载成功:', bankInfoData.value)
    } else {
      console.error('加载余额失败:', result.message)
      // 重置数据
      bankInfoData.value = {
        balance: 0,
        hasBankInfo: false,
        bankInfo: null
      }
      balance.value = 0
    }
  } catch (error) {
    console.error('加载余额失败:', error)
    // 重置数据
    bankInfoData.value = {
      balance: 0,
      hasBankInfo: false,
      bankInfo: null
    }
    balance.value = 0
  }
}

// 确认退出登录
const confirmLogout = () => {
  // 调用退出登录函数
  logout()

  // 关闭弹窗
  showLogoutConfirm.value = false

  // 跳转到登录页面
  router.push('/login')
}

// 路由跳转函数
const goTo = (path) => {
  if (path === '/withdraw') {
    // 跳转到提现页面时传递银行信息数据
    router.push({
      path: '/withdraw',
      query: {
        balance: bankInfoData.value.balance,
        hasBankInfo: bankInfoData.value.hasBankInfo,
        bankInfo: JSON.stringify(bankInfoData.value.bankInfo)
      }
    })
  } else {
    router.push(path)
  }
}

// 修改密码处理函数
const handleChangePassword = () => {
  console.log('=== 修改密码按钮点击事件开始 ===')
  console.log('1. 按钮被点击了 - 事件触发')
  console.log('2. router对象状态:', router ? '存在' : '不存在')
  console.log('3. 当前路由信息:', router?.currentRoute?.value)
  
  // 添加强制刷新测试
  console.log('4. 尝试强制跳转到修改密码页面')
  
  // 使用多种方式确保跳转
  try {
    // 方法1：直接路由跳转
    console.log('方法1: 使用 router.push')
    router.push('/change-password').then(() => {
      console.log('✅ 路由跳转成功 - 方法1')
    }).catch(error1 => {
      console.error('❌ 方法1失败:', error1)
      
      // 方法2：使用 window.location
      console.log('方法2: 使用 window.location')
      window.location.href = '/change-password'
      console.log('✅ 使用 window.location 跳转')
    })
  } catch (error2) {
    console.error('❌ 所有方法都失败:', error2)
    alert('跳转失败，请查看控制台错误信息')
  }
}

// 组件挂载时加载用户信息和余额
onMounted(() => {
  loadUserInfo()
  loadBalance()
})
</script>
